package com.mingqijia.gassafety.console.controller;

import com.gap.basic.base.CommonResponse;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.entity.RunningStrategyExt;
import com.mingqijia.gassafety.shared.constant.MessagePushTypeEnum;
import com.mingqijia.gassafety.shared.constant.OperateRecordEnum;
import com.mingqijia.gassafety.shared.constant.PushServicePeriodLevelEnum;
import com.mingqijia.gassafety.shared.constant.StrategyTypeEnum;
import com.mingqijia.gassafety.shared.log.LogRecord;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.RunningStrategyExtRequest;
import com.mingqijia.gassafety.webserver.request.RunningStrategyRequest;
import com.mingqijia.gassafety.webserver.request.UpdateRunningStrategyRequest;
import com.mingqijia.gassafety.webserver.response.RunningStrategyDetailRes;
import com.mingqijia.gassafety.webserver.response.RunningStrategyRes;
import com.mingqijia.gassafety.webserver.request.SaveRunningStrategyRequest;
import com.mingqijia.gassafety.webserver.service.RunningStrategyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName StrategyController.java
 * @Description TODO
 * @createTime 2023年12月13日
 */
@RestController
@Api(tags = "设备情况通知策略")
@RequestMapping("/business/v1/runningStrategy")
@Slf4j
public class StrategyController {


    @Autowired
    private RunningStrategyService strategyService;
    @Autowired
    HeaderUtil headerUtil;

    /**
     * 新增策略
     *
     * @param request
     * @return
     */
    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_48,commonInfo = "#request.ruleName" )
    @PostMapping("saveWarnStrategy")
    @ApiOperation(value = "新增策略")
    public CommonResponse<Object> saveWarnStrategy(@RequestBody @Valid SaveRunningStrategyRequest request) {
        if (request.getStrategyType() == StrategyTypeEnum.DEVICE_EXPIRATION.getCode()) {
            List<RunningStrategyExtRequest> extDatas = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(request.getExtData())) {
                request.getExtData().stream().forEach(extData -> {
                    if (CollectionUtils.isNotEmpty(extData.getChildren())) {
                        // 前端这里1和2反了，前端1-微信，后端2-微信
                        if (extData.getPushType() != 1 && StringUtils.isEmpty(extData.getPushLevel()) && StringUtils.isEmpty(extData.getPushPhones())) {
                            throw new BizException("客户联系人和其他联系人不能同时为空");
                        }
                        for (RunningStrategyExtRequest item: extData.getChildren()) {
                            if (item.getPushServiceExpireLevel() == null) {
                                throw new BizException("服务到期推送等级不能为空");
                            }
                            if (item.getPushServiceExpireLevel() == PushServicePeriodLevelEnum.PERIOD.getCode()
                                    && (item.getPushNumber() < 1 || item.getPushNumber() > 14)) {
                                throw new BizException("请输入1-14的正整数");
                            }
                            if (item.getPushServiceExpireLevel() == PushServicePeriodLevelEnum.EXPIRED.getCode()
                                    && (item.getPushNumber() < 1 || item.getPushNumber() > 200)) {
                                throw new BizException("请输入1-200的正整数");
                            }
                            item.setPushType(extData.getPushType());
                            item.setPushPhones(extData.getPushPhones());
                            item.setPushLevel(extData.getPushLevel());
                            extDatas.add(item);
                        }
                    }
                });
            }
            request.setExtData(extDatas);
        }
        strategyService.saveWarnStrategy(request,request.getSource());
        return CommonResponse.success(null);
    }

    /**
     * 编辑策略
     *
     * @param request
     * @return
     */
    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_49,commonInfo ="#request.ruleName" ,detail = "'【规则名称：' + #request.ruleName + '】\n'")
    @PostMapping("editWarnStrategy")
    @ApiOperation(value = "编辑策略")
    public CommonResponse<Object> editWarnStrategy(@RequestBody @Valid SaveRunningStrategyRequest request) {
        if (request.getStrategyType() == StrategyTypeEnum.DEVICE_EXPIRATION.getCode()) {
            List<RunningStrategyExtRequest> extDatas = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(request.getExtData())) {
                request.getExtData().stream().forEach(extData -> {
                    if (CollectionUtils.isNotEmpty(extData.getChildren())) {
                        // 前端这里1和2反了，前端1-微信，后端2-微信
                        if (extData.getPushType() != 1 && StringUtils.isEmpty(extData.getPushLevel()) && StringUtils.isEmpty(extData.getPushPhones())) {
                            throw new BizException("客户联系人和其他联系人不能同时为空");
                        }
                        for (RunningStrategyExtRequest item: extData.getChildren()) {
                            if (item.getPushServiceExpireLevel() == null) {
                                throw new BizException("服务到期推送等级不能为空");
                            }
                            if (item.getPushServiceExpireLevel() == PushServicePeriodLevelEnum.PERIOD.getCode()
                                    && (item.getPushNumber() < 1 || item.getPushNumber() > 14)) {
                                throw new BizException("请输入1-14的正整数");
                            }
                            if (item.getPushServiceExpireLevel() == PushServicePeriodLevelEnum.EXPIRED.getCode()
                                    && (item.getPushNumber() < 1 || item.getPushNumber() > 200)) {
                                throw new BizException("请输入1-200的正整数");
                            }
                            item.setPushType(extData.getPushType());
                            item.setPushPhones(extData.getPushPhones());
                            item.setPushLevel(extData.getPushLevel());
                            extDatas.add(item);
                        }
                    }
                });
            }
            request.setExtData(extDatas);
        }
        strategyService.editWarnStrategy(request,request.getSource());
        return CommonResponse.success(null);
    }

    /**
     * 查询策略列表
     *
     * @param
     * @return
     */
    @PostMapping("warnStrategyList")
    @ApiOperation(value = "查询策略列表")
    public CommonResponse<PageUtil<RunningStrategyRes>> warnStrategyList(@RequestBody RunningStrategyRequest request) {
        request.setTemplateType(headerUtil.getTemplateType());
        return CommonResponse.success(strategyService.warnStrategyList(request));
    }

    /**
     * 策略详情
     */
    @GetMapping("detail")
    @ApiOperation(value = "策略详情")
    public CommonResponse<RunningStrategyDetailRes> strategyDetail(@RequestParam("id") Long id){
        RunningStrategyDetailRes res = strategyService.getStrategyDetail(id);
        if (res.getStrategyType() == StrategyTypeEnum.DEVICE_EXPIRATION.getCode()) {
            Map<Integer, List<RunningStrategyExtRequest>> extMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(res.getExtData())) {
                res.getExtData().stream().forEach(x -> {
                    if (extMap.get(x.getPushType()) == null) {
                        extMap.put(x.getPushType(), new ArrayList<>());
                    }
                    if (extMap.get(x.getCallSendNote()) == null) {
                        extMap.put(x.getCallSendNote(), new ArrayList<>());
                    }
                    extMap.get(x.getPushType()).add(x);
                });
            }
            List<RunningStrategyExtRequest> extDatas = new ArrayList<>();
            extMap.forEach((key, value) -> {
                //log.info("value的值为:{}", value);
                RunningStrategyExtRequest extData = new RunningStrategyExtRequest();
                extData.setPushType(key);
                extData.setChildren(value);
                if (CollectionUtils.isNotEmpty(value)) {
                    extData.setPushPhones(value.get(0).getPushPhones());
                    extData.setPushLevel(value.get(0).getPushLevel());
                    extData.setCallSendNote(value.get(0).getCallSendNote());
                }
                extDatas.add(extData);
            });
            res.setExtData(extDatas);

        }
        return CommonResponse.success(res);
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_50)
    @PostMapping("disable")
    @ApiOperation(value = "(批量)禁用/启用策略")
    public CommonResponse<Object> disable(@RequestBody @Valid UpdateRunningStrategyRequest request){
         strategyService.activeStrategy(request);
        return CommonResponse.success(null);
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_54)
    @PostMapping("delete")
    @ApiOperation(value = "删除")
    public CommonResponse<Object> deleteStrategy(@RequestBody @Valid UpdateRunningStrategyRequest request){
        strategyService.deleteStrategy(request);
        return CommonResponse.success(null);
    }

}